import saleOrderService, { type PageListReq } from "@/api/services/wms/saleOrderService";
import TableDictTag from "@/components/grid/TableDictTag";
import { TableToolbar } from "@/components/grid/TableToolbar";
import useDictionary from "@/hooks/system/useDictionary";
import { t } from "@/locales/i18n";
import SingleCustomerSelector from "@/pages/components/selector/SingleCustomerSelect";
import SingleUserSelector from "@/pages/components/selector/SingleUserSelect";
import { UserAddOutlined } from "@ant-design/icons";
import { Button, Card, Col, DatePicker, Drawer, Form, Input, Row, Select, Space, Spin, Tabs } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import dayjs from "dayjs";
import { useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import type { CrmSalesOrder } from "./entity";
import CrmSalesDetailPage, { type CrmSalesDetailHandles } from "./saleDetail";

export default function CrmSalesOrderPage() {
	const saleDetailRef = useRef<CrmSalesDetailHandles>(null);

	const [loading, setLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
	const [queryParams, setQueryParams] = useState<PageListReq>({
		code: undefined,
		type: undefined,
		orderDate: undefined,
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<CrmSalesOrder[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [editingData, setEditingData] = useState<CrmSalesOrder | null>(null);
	const [form] = Form.useForm();
	const [isView, setIsView] = useState(true);

	const [customerSelectVisible, setCustomerSelectVisible] = useState(false);
	const [userSelectVisiable, setUserSelectVisiable] = useState(false);

	//动态设置表格高度
	const [tableScrollY, setTableScrollY] = useState(0);
	const PAGE_OFFSET_HEIGHT = 403;
	const updateTableHeight = () => {
		const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
		setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		updateTableHeight(); // 初始化
		window.addEventListener("resize", updateTableHeight);
		return () => window.removeEventListener("resize", updateTableHeight);
	}, []);

	const typeOptions = useDictionary("sale_order_type");
	const statusOptions = useDictionary("common_order_status");

	const columns: ColumnsType<CrmSalesOrder> = [
		{
			title: "订单编码",
			width: 120,
			key: "code",
			dataIndex: "code",
		},
		{
			title: "订单类型",
			width: 120,
			key: "type",
			dataIndex: "type",
			render: (_, record) => <TableDictTag dictCode="sale_order_type" value={record.type ?? ""} />,
		},
		{
			title: "客户",
			width: 120,
			key: "customerName",
			dataIndex: "customerName",
		},
		{
			title: "订单状态",
			width: 120,
			key: "status",
			dataIndex: "status",
			render: (_, record) => <TableDictTag dictCode="common_order_status" value={record.status ?? ""} />,
		},
		{
			title: "订单日期",
			width: 120,
			key: "orderDate",
			dataIndex: "orderDate",
		},
		{
			title: "进度",
			width: 120,
			key: "schedule",
			dataIndex: "schedule",
		},
		{
			title: "销售员",
			width: 120,
			key: "sellerName",
			dataIndex: "sellerName",
		},
		{
			title: "备注",
			width: 120,
			key: "remark",
			dataIndex: "remark",
		},
		{
			title: "操作",
			fixed: "right",
			key: "operation",
			align: "center",
			width: 100,
			render: (_, record) => (
				<Space>
					<Button type="link" onClick={() => handleView(record)}>
						{t("common.view")}
					</Button>
					<Button type="link" onClick={() => handleEdit(record)}>
						{t("common.edit")}
					</Button>
				</Space>
			),
		},
	];

	const [selectedValues, setSelectedValues] = useState<string[]>(() =>
		columns.filter((col) => col.key !== "operation").map((col) => (col.key ? String(col.key) : "")),
	);

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	const filteredColumns = useMemo(() => {
		return [...columns.filter((col) => selectedValues.includes(String(col.key)) || col.key === "operation")].sort(
			(a, b) => {
				const originalIndex = columns.findIndex((c) => c.key === a.key);
				const targetIndex = columns.findIndex((c) => c.key === b.key);
				return originalIndex - targetIndex;
			},
		);
	}, [selectedValues]);

	//加载表格数据
	const fetchPageList = () => {
		setLoading(true);
		saleOrderService
			.pageList(queryParams)
			.then((res) => {
				setList(res.records);
				setTotal(res.total);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		fetchPageList();
	}, [queryParams]);

	//选择其他页
	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	//触发编辑按钮
	const handleEdit = (crmSalesOrder: CrmSalesOrder) => {
		setEditingData(crmSalesOrder);
		form.setFieldsValue({
			...crmSalesOrder,
			orderDate: crmSalesOrder.orderDate ? dayjs(crmSalesOrder.orderDate) : undefined,
		});

		setDrawerVisible(true);
		setIsView(false);
	};

	//触发视图按钮
	const handleView = (crmSalesOrder: CrmSalesOrder) => {
		setEditingData(crmSalesOrder);
		form.setFieldsValue(crmSalesOrder);
		setIsView(true);
		setDrawerVisible(true);
	};

	//提交表单数据
	const handleSubmit = async (values: CrmSalesOrder) => {
		try {
			setSubmitLoading(true);

			//销售订单明细
			const deleteSaleDetailIds = saleDetailRef.current?.getDeleteIds();
			const addSaleDetails = saleDetailRef.current?.getAddList();
			const updateSaleDetails = saleDetailRef.current?.getUpdateList();

			const data = {
				...values,
				id: editingData?.id,
				deleteSaleDetailIds: deleteSaleDetailIds,
				orderDate: values.orderDate ? dayjs(values.orderDate).format("YYYY-MM-DD") : undefined,
				addSaleDetails: addSaleDetails,
				updateSaleDetails: updateSaleDetails,
			};
			if (editingData) {
				await saleOrderService.update(data);
				toast.success("更新销售订单成功");
			} else {
				await saleOrderService.add(data);
				toast.success("创建销售订单成功");
			}
			setDrawerVisible(false);
			setEditingData(null);
			form.resetFields();
			fetchPageList();
		} catch (error) {
			toast.error(`保存失败: ${error.message}`);
		} finally {
			setSubmitLoading(false);
		}
	};

	const handleDrawerClose = () => {
		setDrawerVisible(false);
		setEditingData(null);
		form.resetFields();
	};

	const handleAdd = () => {
		setEditingData(null);
		form.resetFields();
		form.setFieldsValue({
			type: "STANDARD",
			status: "PREPARE",
		});
		setDrawerVisible(true);
		setIsView(false);
	};

	const handleDelete = async () => {
		try {
			setLoading(true);
			await saleOrderService.remove(selectedRowKeys);
			toast.success("删除销售订单成功");
			setSelectedRowKeys([]);
			fetchPageList();
		} catch (error) {
			toast.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	const showCustomerSelect = () => {
		setCustomerSelectVisible(true);
	};

	const handleCustomerSelected = (customer: any) => {
		form.setFieldsValue({
			customerName: customer.client_name,
			customerId: customer.id,
		});
		setCustomerSelectVisible(false);
	};

	const showUserSelect = () => {
		setUserSelectVisiable(true);
	};

	const handleSelectUser = (user?: UserInfo) => {
		form.setFieldsValue({
			seller: user?.id,
			sellerName: user?.name,
		});
		setUserSelectVisiable(false);
	};

	return (
		<Spin spinning={submitLoading} tip="加载中..." size="large">
			<Card className="mb-4">
				<Form
					layout="inline"
					onFinish={(values) => {
						setQueryParams((prev) => ({
							...prev,
							...values,
							page: 1,
						}));
					}}
				>
					<Form.Item name="code" label="订单编码">
						<Input placeholder="请输入订单编码" allowClear />
					</Form.Item>
					<Form.Item name="type" label="订单类型">
						<Input placeholder="请输入订单类型" allowClear />
					</Form.Item>
					<Form.Item name="orderDate" label="订单日期">
						<Input placeholder="请输入订单日期" allowClear />
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button
							className="ml-2"
							onClick={() => {
								setQueryParams({ page: 1, pageSize: 10 });
							}}
						>
							重置
						</Button>
					</Form.Item>
				</Form>
			</Card>
			<div className="h-4" />
			<Card>
				<div className="flex justify-between mb-4">
					<div className="flex gap-2">
						<Button type="primary" onClick={handleAdd}>
							新增
						</Button>
						<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
							删除
						</Button>
					</div>
					<TableToolbar
						onRefresh={() => setQueryParams((prev) => ({ ...prev }))}
						onSizeChange={setTableSize}
						columns={columns}
						selectedValues={selectedValues}
						onColumnChange={setSelectedValues}
					/>
				</div>
				<Table
					rowKey="id"
					size={tableSize}
					scroll={{ x: "max-content", y: tableScrollY }}
					loading={loading}
					pagination={{
						total,
						current: queryParams.page,
						pageSize: queryParams.pageSize,
						onChange: handlePageChange,
					}}
					columns={filteredColumns}
					dataSource={list}
					rowSelection={{
						type: "checkbox",
						selectedRowKeys: selectedRowKeys,
						onChange: (selectedKeys) => {
							setSelectedRowKeys(selectedKeys as string[]);
						},
					}}
				/>
			</Card>
			<Drawer
				title={editingData ? "编辑销售订单" : "新增销售订单"}
				width={800}
				open={drawerVisible}
				onClose={handleDrawerClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handleDrawerClose}>取消</Button>
						{!isView && (
							<Button type="primary" onClick={() => form.submit()}>
								确定
							</Button>
						)}
					</div>
				}
			>
				<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit} disabled={isView}>
					<Row gutter={16}>
						<Col span={12}>
							<Form.Item
								name="code"
								label="订单编码"
								rules={[
									{
										required: true,
										message: "请填写订单编码",
									},
								]}
							>
								<Input placeholder="请输入订单编码" allowClear />
							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item
								name="type"
								label="订单类型"
								rules={[
									{
										required: true,
										message: "请填写订单类型",
									},
								]}
							>
								<Select options={typeOptions} allowClear />
							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item name="customerId" label="客户" hidden>
								<Input placeholder="请输入客户" allowClear />
							</Form.Item>
							<Form.Item name="customerName" label="客户">
								<Input.Search
									placeholder="请输入客户"
									allowClear
									enterButton={<UserAddOutlined />}
									onSearch={showCustomerSelect}
								/>
							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item name="seller" label="销售员ID" hidden>
								<Input />
							</Form.Item>
							<Form.Item
								name="sellerName"
								label="销售员"
								rules={[
									{
										required: true,
										message: "请选择销售员",
									},
								]}
							>
								<Input.Search
									placeholder="请选择销售员"
									allowClear
									enterButton={<UserAddOutlined />}
									onSearch={showUserSelect}
								/>
							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item
								name="orderDate"
								label="订单日期"
								rules={[
									{
										required: true,
										message: "请填写订单日期",
									},
								]}
							>
								<DatePicker
									style={{ width: "100%" }}
									format="YYYY-MM-DD"
									onChange={(date) => (date ? date.format("YYYY-MM-DD") : null)}
								/>
							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item name="status" label="订单状态">
								<Select options={statusOptions} disabled />
							</Form.Item>
						</Col>
						<Col span={24}>
							<Form.Item name="remark" label="备注" labelCol={{ span: 3 }} wrapperCol={{ span: 21 }}>
								<Input.TextArea />
							</Form.Item>
						</Col>
					</Row>

					<Tabs
						defaultActiveKey="1"
						items={[
							{
								key: "1  ",
								label: "销售订单明细",
								children: <CrmSalesDetailPage ref={saleDetailRef} parentId={editingData?.id} />,
							},
						]}
					/>
				</Form>
			</Drawer>

			{/* 用户选择器 */}
			<SingleUserSelector
				open={userSelectVisiable}
				onCancel={() => setUserSelectVisiable(false)}
				onOk={(selectUser) => handleSelectUser(selectUser)}
			/>

			{/* 客户选择器 */}
			<SingleCustomerSelector
				open={customerSelectVisible}
				onCancel={() => setCustomerSelectVisible(false)}
				onOk={(item) => handleCustomerSelected(item)}
			/>
		</Spin>
	);
}
